package com.csair.platform.cit.service.biz.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.csair.platform.cit.service.biz.ICitZcjszjkcmxbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.csair.invoice.common.base.util.BeanUtils;
import com.csair.invoice.common.base.util.StringUtil;
import com.csair.invoice.common.base.util.collection.CollectionUtil;
import com.csair.invoice.common.base.vo.JsonResult;
import com.csair.platform.cit.facade.exception.CitBizException;
import com.csair.platform.cit.facade.model.CitQueryParam;
import com.csair.platform.cit.facade.model.CitSendParam;
import com.csair.platform.cit.facade.model.InitDataVo;
import com.csair.platform.cit.facade.model.a200000.CitMssrBmVo;
import com.csair.platform.cit.facade.model.a200000.CitMssrGridVo;
import com.csair.platform.cit.facade.model.a200000.CitMssrSaveVo;
import com.csair.platform.cit.facade.model.a200000.CitNsrxxVo;
import com.csair.platform.cit.facade.model.a200000.CitQtxxVo;
import com.csair.platform.cit.facade.model.a200000.CitSbbxxVo;
import com.csair.platform.cit.facade.model.a200000.CitYhfbxxVo;
import com.csair.platform.cit.service.biz.IA200000Service;
import com.csair.platform.cit.service.biz.InitDataService;
import com.csair.platform.cit.service.dao.a200000.CitMssrBmRepository;
import com.csair.platform.cit.service.dao.a200000.CitMssrGridRepository;
import com.csair.platform.cit.service.dao.a200000.CitNsrxxRepository;
import com.csair.platform.cit.service.dao.a200000.CitQtxxRepository;
import com.csair.platform.cit.service.dao.a200000.CitSbbxxRepository;
import com.csair.platform.cit.service.dao.a200000.CitYhfbxxRepository;
import com.csair.platform.cit.service.dao.a202000.CitFzjgFormRepository;
import com.csair.platform.cit.service.dao.a202000.CitZjgxxFormRepository;
import com.csair.platform.cit.service.entity.CitDeclareRecord;
import com.csair.platform.cit.service.entity.CitFzjgForm;
import com.csair.platform.cit.service.entity.CitMssrBm;
import com.csair.platform.cit.service.entity.CitMssrGrid;
import com.csair.platform.cit.service.entity.CitNsrxx;
import com.csair.platform.cit.service.entity.CitQtxx;
import com.csair.platform.cit.service.entity.CitSbbxx;
import com.csair.platform.cit.service.entity.CitYhfbxx;
import com.csair.platform.cit.service.entity.CitZjgxxForm;
import com.csair.platform.usercenter.facade.model.user.UserVo;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * [主表数据]服务实现类
 * @author ：caoyu
 * 
 */
@Slf4j
@Service
public class A200000ServiceImpl extends InitBaseServiceImpl implements IA200000Service {
    
    /**
     * 纳税人信息dao
     */
    @Autowired
    CitNsrxxRepository nsrxxDao;

    /**
     * 优惠附表信息dao
     */
    @Autowired
    CitYhfbxxRepository yhfbxxDao;
    
    /**
     * 申报表信息dao
     */
    @Autowired
    CitSbbxxRepository sbbxxDao;

    /**
     * 免税收入7.1数据dao
     */
    @Autowired
    CitMssrGridRepository mssrxxDao;
    
    /**
     * 其他信息dao
     */
    @Autowired
    CitQtxxRepository qtxxDao;
    
    /**
     * 分配表的总机构信息dao
     */
    @Autowired
    CitZjgxxFormRepository zjgxxFormDao;
    
    /**
     * 分配表的分支机构信息dao
     */
    @Autowired
    CitFzjgFormRepository fzjgFormDao;    
    
    /**
     * 期初数据服务
     */
    @Autowired
    InitDataService initDataService;
    
    /**
     * 主表优惠编码dao
     */
    @Autowired
    CitMssrBmRepository mssrBmDao;

    @Autowired
    ICitZcjszjkcmxbService iCitZcjszjkcmxbService;


    @Override
    public void saveNsrxx(CitNsrxxVo nsrxxVo) {
        this.checkData(nsrxxVo.getNsrsbh(), nsrxxVo.getSkssqq(), nsrxxVo.getSkssqz());
        List<CitNsrxx> listDb = this.queryNsrxx(nsrxxVo.getNsrsbh(), nsrxxVo.getSkssqq(), nsrxxVo.getSkssqz());
        if (CollectionUtil.isNotEmpty(listDb)) {
            nsrxxDao.deleteAll(listDb);
        }
        CitNsrxx entity = new CitNsrxx();
        BeanUtils.copyProperties(nsrxxVo, entity);
        entity.setXzqhszDm(""); //跨省总机构行政区划代码（省级行政区划代码），当总机构在外省的分支机构申报时需要传入，调用初始化服务时也需要传入，传空
        entity.setSbsxDm1(""); //申报属性代码，默认传空
        entity.setYjfs(1); //预缴方式：1按照实际利润额预缴|2按照上一纳税年度应纳税所得额平均额预缴|3按照税务机关确定的其他方法预缴，默认传1
        entity.setSbqylx(1); //企业类型：0一般企业|1跨地区经营汇总纳税企业总机构|2跨地区经营汇总纳税企业分支机构，默认传1
        nsrxxDao.save(entity);
        log.info("保存[主表数据-纳税人信息]成功。");
    }

    @Override
    public void saveYhfbxx(CitYhfbxxVo yhfbxxVo) {
        this.checkData(yhfbxxVo.getNsrsbh(), yhfbxxVo.getSkssqq(), yhfbxxVo.getSkssqz());
        Map<String, Object> map = this.cleanThousandth(BeanUtils.object2Map(yhfbxxVo));
        CitYhfbxxVo vo = BeanUtils.map2Bean(map, CitYhfbxxVo.class);
        List<CitYhfbxx> listDb = this.queryYhfbxx(yhfbxxVo.getNsrsbh(), yhfbxxVo.getSkssqq(), yhfbxxVo.getSkssqz());        
        if (CollectionUtil.isNotEmpty(listDb)) {
            yhfbxxDao.deleteAll(listDb);
        }
        CitYhfbxx entity = new CitYhfbxx();
        BeanUtils.copyProperties(vo, entity);
        yhfbxxDao.save(entity);
        log.info("保存[主表数据-优惠附表信息]成功。");
    }

    @Override
    public void saveSbbxx(CitSbbxxVo sbbxxVo) {
        this.checkData(sbbxxVo.getNsrsbh(), sbbxxVo.getSkssqq(), sbbxxVo.getSkssqz());
        Map<String, Object> map = this.cleanThousandth(BeanUtils.object2Map(sbbxxVo));
        CitSbbxxVo vo = BeanUtils.map2Bean(map, CitSbbxxVo.class);
        List<CitSbbxx> listDb = this.querySbbxx(sbbxxVo.getNsrsbh(), sbbxxVo.getSkssqq(), sbbxxVo.getSkssqz());
        if (CollectionUtil.isNotEmpty(listDb)) {
            sbbxxDao.deleteAll(listDb);
        }
        CitSbbxx entity = new CitSbbxx();
        BeanUtils.copyProperties(vo, entity);
        //根据行次-16，18，19行同步修改分配表数据
        CitZjgxxForm zjgxx = this.queryZjgxx(entity.getNsrsbh(), entity.getSkssqq(), entity.getSkssqz());
        BigDecimal ybtsdseLj = new BigDecimal(entity.getYbtsdseLj()); //行次-16 应纳所得税额
        BigDecimal zjgyftsdseBq = new BigDecimal(entity.getZjgyftsdseBq()); //行次-18 总机构分摊所得税额
        BigDecimal czjzfpsdseBq = new BigDecimal(entity.getCzjzfpsdseBq()); //行次-19 总机构财政集中分配所得税额
        BigDecimal fpse = BigDecimal.ZERO; //行次-20
        if (zjgxx != null) {
            BigDecimal fzjgftdsdse = ybtsdseLj.subtract(zjgyftsdseBq).subtract(czjzfpsdseBq); //分支机构分摊所得税额 = 16行-18行-19行
            zjgxx.setYnsdse(ybtsdseLj + "");
            zjgxx.setFzjgftdsdse(zjgyftsdseBq + "");
            zjgxx.setZjgczjzfpsdse(czjzfpsdseBq + "");
            zjgxx.setFzjgftdsdse(fzjgftdsdse + "");
            zjgxxFormDao.save(zjgxx);
            log.info("更新[分配表数据-总机构信息]成功。");
            List<CitFzjgForm> listFzjgxx = this.queryFzjgxx(zjgxx);
            if (CollectionUtil.isNotEmpty(listFzjgxx)) {
                BigDecimal totalFzjgfpse = BigDecimal.ZERO; //其他各项分支机构分配税额之和
                for (CitFzjgForm fzjgxx : listFzjgxx) {
                    BigDecimal fpbl = new BigDecimal(fzjgxx.getFpbl()); //分配比例
                    BigDecimal fzjgfpse = fzjgftdsdse.multiply(fpbl).setScale(2, BigDecimal.ROUND_HALF_UP); //分支机构分配税额 = 分支机构分摊所得税额 * 分配比例
                    if (!sbbxxVo.getNsrsbh().equals(fzjgxx.getFzjgnsrsbh())) {
                        fzjgxx.setFzjgfpse(fzjgfpse + ""); 
                        totalFzjgfpse = totalFzjgfpse.add(fzjgfpse);
                    }
                }
                //分支机构的股份税号的分支机构分配税额 = 分支机构分摊所得税额 - 其他各项分支机构分配税额之和
                for (CitFzjgForm fzjgxx : listFzjgxx) {
                    if (sbbxxVo.getNsrsbh().equals(fzjgxx.getFzjgnsrsbh())) {
                        fpse = fzjgftdsdse.subtract(totalFzjgfpse);
                        fzjgxx.setFzjgfpse(fpse + ""); 
                        entity.setDlscjybmftbl(fzjgxx.getFpbl()); //主表行次19-总机构填报-总机构具有主体生产经营职能部门分摊比例 = 分配表分支机构数据最后一行股份税号的分配比例
                        entity.setZjgdlscjybmyftsdseBq(fpse + ""); //主表行次20-总机构填报-总机构具有主体生产经营职能的部门分摊所得税额 = 分配表分支机构数据最后一行股份税号的分摊税额
                        entity.setZjgybtsdseBq(zjgyftsdseBq.add(czjzfpsdseBq).add(fpse) + ""); //17行=18行+19行+20行
                        break;
                    }
                }
                fzjgFormDao.saveAll(listFzjgxx);
                log.info("更新[分配表数据-分支机构信息]成功。");
            }
        }
        //根据分摊表最后一行数据修正主表数据
        BigDecimal mzzzdqdfjmBq = BigDecimal.ZERO; //行次-23
        BigDecimal zyjsrsjynseBq = BigDecimal.ZERO; //行次-FZ1
        BigDecimal dfjsrynseBq = BigDecimal.ZERO; //行次-FZ2
        if ("91440000100017600N".equals(sbbxxVo.getNsrsbh())) { //股份
            zyjsrsjynseBq = (zjgyftsdseBq.add(fpse)).multiply(new BigDecimal("0.6")).setScale(2, BigDecimal.ROUND_HALF_UP).add(czjzfpsdseBq);
            entity.setZyjsrsjynseBq(zyjsrsjynseBq + ""); //FZ1=(18行+20行)*60%+19行
            dfjsrynseBq = (zjgyftsdseBq.add(fpse)).multiply(new BigDecimal("0.4")).setScale(2, BigDecimal.ROUND_HALF_UP);
            entity.setDfjsrynseBq(dfjsrynseBq + ""); //FZ2=(18行+20行)*40%
            mzzzdqdfjmBq = dfjsrynseBq.multiply(new BigDecimal(entity.getJzfd())).setScale(2, BigDecimal.ROUND_HALF_UP);
        } else if ("91440000100005896P".equals(sbbxxVo.getNsrsbh())) { //集团
            zyjsrsjynseBq = ybtsdseLj.multiply(new BigDecimal("0.6")).setScale(2, BigDecimal.ROUND_HALF_UP);
            entity.setZyjsrsjynseBq(zyjsrsjynseBq + ""); //FZ1=16行*60%
            dfjsrynseBq = ybtsdseLj.multiply(new BigDecimal("0.4")).setScale(2, BigDecimal.ROUND_HALF_UP);
            entity.setDfjsrynseBq(dfjsrynseBq + ""); //FZ2=16行*40%    
            mzzzdqdfjmBq = dfjsrynseBq.multiply(new BigDecimal(entity.getJzfd())).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        entity.setMzzzdqdfjmBq(mzzzdqdfjmBq + ""); //23行=FZ2*减征幅度
        BigDecimal dfjsrsjynseBq = dfjsrynseBq.subtract(mzzzdqdfjmBq);
        entity.setDfjsrsjynseBq(dfjsrsjynseBq + ""); //FZ3=FZ2-23行
        BigDecimal sjybtsdseBq = zyjsrsjynseBq.add(dfjsrsjynseBq);
        entity.setSjybtsdseBq(sjybtsdseBq + ""); //24行=FZ1+FZ3
        sbbxxDao.save(entity);
        log.info("保存[主表数据-申报表信息]成功。");
    }
    
    @Override
    public void saveMssrxx(CitMssrSaveVo mssrxxVo, String hc) {
    	String nsrsbh = mssrxxVo.getNsrsbh();
    	String skssqq = mssrxxVo.getSkssqq();
    	String skssqz = mssrxxVo.getSkssqz();
        this.checkData(nsrsbh, skssqq, skssqz);
        List<CitMssrGrid> listDb = this.queryMssrxx(nsrsbh, skssqq, skssqz, hc);        
        if (CollectionUtil.isNotEmpty(listDb)) {
            mssrxxDao.deleteAll(listDb);
        }
        List<CitMssrGridVo> list = mssrxxVo.getMssrxx();
        if (CollectionUtil.isEmpty(list)) { //可选项，数据为空不保存
            return;
        }
        List<CitMssrGrid> listUpdate = new ArrayList<>();
        for (CitMssrGridVo vo2 : list) {
            Map<String, Object> map = this.cleanThousandth(BeanUtils.object2Map(vo2));
            CitMssrGridVo vo = BeanUtils.map2Bean(map, CitMssrGridVo.class);
            CitMssrGrid entity = new CitMssrGrid();
            BeanUtils.copyProperties(vo, entity);
            entity.setNsrsbh(nsrsbh);
            entity.setSkssqq(skssqq);
            entity.setSkssqz(skssqz);
            entity.setEwbhxh(vo.getXh()); //二维表行序号
            listUpdate.add(entity);
        }
        mssrxxDao.saveAll(listUpdate);
        log.info("保存[主表数据-优惠减免数据 " + hc + ".*]成功。");
    }

    @Override
    public void saveQtxx(CitQtxxVo qtxxVo) {
        this.checkData(qtxxVo.getNsrsbh(), qtxxVo.getSkssqq(), qtxxVo.getSkssqz());
        List<CitQtxx> listDb = this.queryQtxx(qtxxVo.getNsrsbh(), qtxxVo.getSkssqq(), qtxxVo.getSkssqz());        
        if (CollectionUtil.isNotEmpty(listDb)) {
            qtxxDao.deleteAll(listDb);
        }
        CitQtxx entity = new CitQtxx();
        BeanUtils.copyProperties(qtxxVo, entity);
        entity.setSfdlsb("N"); //是否代理申报||Y,N,默认为N
        entity.setDlsbzjjg(""); //代理申报中介机构,传空
        entity.setBlrysfzjlxDm("201"); //办理人员身份证件类型，|取自代码表DM_GY_SFZJLX, 201-居民身份证
        entity.setSlr("广东省电子税务局"); //受理人，默认为：广东省电子税务局
        entity.setSlrq(""); //受理日期，传空
        entity.setDljgtyshxydm(""); //代理机构统一社会信用代码，适用于2019年及以后年度申报，，传空
        qtxxDao.save(entity);
        log.info("保存[主表数据-其他信息]成功。");
    }

    @Override
    public JsonResult<JSONObject> query(CitQueryParam param, UserVo user, boolean isJson) {
        String taxNo = param.getNsrsbh();
        String skssqq = param.getSkssqq();
        String skssqz = param.getSkssqz();
        
        //获取申报进度
        CitSendParam param2 = new CitSendParam();
        BeanUtils.copyProperties(param, param2);
        CitDeclareRecord record = this.queryDeclareRecord(param2);

        //获取期初数据
        InitDataVo dataInit = null; 
        if (record == null) {
            try {
                JsonResult<InitDataVo> initResult = initDataService.getInitData(param, user);
                List<InitDataVo> datasInit = initResult.getData();
                if (CollectionUtil.isNotEmpty(datasInit)) {
                    dataInit = datasInit.get(0);
                }
            } catch (Exception e) {
                log.error("获取期初数据异常，" + e.getMessage(), e);
            }
        }        
        
        //1.主表数据-纳税人信息
        List<CitNsrxx> listNsrxx = this.queryNsrxx(taxNo, skssqq, skssqz);
        if (CollectionUtil.isEmpty(listNsrxx)) {
            CitNsrxx nsrxx = new CitNsrxx();
            nsrxx.setNsrsbh(taxNo);
            nsrxx.setSkssqq(skssqq);
            nsrxx.setSkssqz(skssqz);
            listNsrxx.add(nsrxx);
        }        
        //2.主表数据-优惠附表信息
        List<CitYhfbxx> listYhfbxx = this.queryYhfbxx(taxNo, skssqq, skssqz);
        if (CollectionUtil.isEmpty(listYhfbxx)) {
            CitYhfbxx yhfbxx = new CitYhfbxx();
            yhfbxx.setNsrsbh(taxNo);
            yhfbxx.setSkssqq(skssqq);
            yhfbxx.setSkssqz(skssqz);
            if (dataInit != null) { //根据期初数据赋值(每季度的期初期末从业人数和资产总额）
                yhfbxx.setQccyrs1(dataInit.getQccyrs1());
                yhfbxx.setQccyrs2(dataInit.getQccyrs2());
                yhfbxx.setQccyrs3(dataInit.getQccyrs3());
                yhfbxx.setQccyrs4(dataInit.getQccyrs4());
                yhfbxx.setQmcyrs1(dataInit.getQmcyrs1());
                yhfbxx.setQmcyrs2(dataInit.getQmcyrs2());
                yhfbxx.setQmcyrs3(dataInit.getQmcyrs3());
                yhfbxx.setQmcyrs4(dataInit.getQmcyrs4());
                yhfbxx.setQczcze1(dataInit.getQczcze1());
                yhfbxx.setQczcze2(dataInit.getQczcze2());
                yhfbxx.setQczcze3(dataInit.getQczcze3());
                yhfbxx.setQczcze4(dataInit.getQczcze4());
                yhfbxx.setQmzcze1(dataInit.getQmzcze1());
                yhfbxx.setQmzcze2(dataInit.getQmzcze2());
                yhfbxx.setQmzcze3(dataInit.getQmzcze3());
                yhfbxx.setQmzcze4(dataInit.getQmzcze4());
            }
            listYhfbxx.add(yhfbxx);
        }
        //3.主表数据-申报表信息
        List<CitSbbxx> listSbbxx = this.querySbbxx(taxNo, skssqq, skssqz);
        if (CollectionUtil.isEmpty(listSbbxx)) {
            CitSbbxx sbbxx = new CitSbbxx();
            sbbxx.setNsrsbh(taxNo);
            sbbxx.setSkssqq(skssqq);
            sbbxx.setSkssqz(skssqz);
            if (dataInit != null) { //根据期初数据赋值
                sbbxx.setSjyyjsdseLj(dataInit.getHc14_sjyyjsdseLj()); //申报表数据-行次14-实际已缴所得税额累计
                sbbxx.setTdywyjzsdseLj(dataInit.getHc15_tdywyjzsdseLj()); //申报表数据-行次15-特定业务预缴（征）所得税额累计
                sbbxx.setZjgftbl(dataInit.getHc18_zjgftbl()); //申报表数据-行次18-总机构填报-总机构分摊比例
                sbbxx.setZjgczjzftbl(dataInit.getHc19_zjgczjzftbl()); //申报表数据-行次19-总机构填报-财政集中分配比例
                sbbxx.setFzjgftbl(dataInit.getHc20_fzjgftbl()); //申报表数据-行次20-总机构填报-全部分支机构分摊比例
            }
            sbbxx.setSlLj("0.25"); //行次11-默认25%
            listSbbxx.add(sbbxx);
        }
        //分摊表数据更新主表数据
        if (record == null) {
            CitFzjgForm nhFzjgxx = this.queryNhFzjgData(taxNo, skssqq, skssqz);
            if (nhFzjgxx != null) {
                String fpbl = nhFzjgxx.getFpbl();
                String fpse = nhFzjgxx.getFzjgfpse();
                for (CitSbbxx entity : listSbbxx) {
                    entity.setDlscjybmftbl(fpbl); //主表行次19-总机构填报-总机构具有主体生产经营职能部门分摊比例 = 分配表分支机构数据最后一行股份税号的分配比例
                    entity.setZjgdlscjybmyftsdseBq(fpse); //主表行次20-总机构填报-总机构具有主体生产经营职能的部门分摊所得税额 = 分配表分支机构数据最后一行股份税号的分摊税额
                }
            }
        }
        
        //4.主表数据-优惠减免数据
        //7.*
        List<CitMssrGrid> listMssrxx = this.queryMssrxx(taxNo, skssqq, skssqz, "7");
        List<CitMssrGridVo> listMssrxxVo = new ArrayList<>();
        for (CitMssrGrid mssrEntity : listMssrxx) {
            CitMssrGridVo mssrVo = new CitMssrGridVo();
            BeanUtils.copyProperties(mssrEntity, mssrVo);
            mssrVo.setXh(mssrEntity.getEwbhxh());
            listMssrxxVo.add(mssrVo);
        }
        //8.*
        List<CitMssrGrid> listSdjmxx = this.queryMssrxx(taxNo, skssqq, skssqz, "8");
        List<CitMssrGridVo> listSdjmxxVo = new ArrayList<>();
        for (CitMssrGrid sdjmEntity : listSdjmxx) {
            CitMssrGridVo sdjmVo = new CitMssrGridVo();
            BeanUtils.copyProperties(sdjmEntity, sdjmVo);
            sdjmVo.setXh(sdjmEntity.getEwbhxh());
            listSdjmxxVo.add(sdjmVo);
        }
        //13.*
        List<CitMssrGrid> listJmsdxx = this.queryMssrxx(taxNo, skssqq, skssqz, "13");
        List<CitMssrGridVo> listJmsdxxVo = new ArrayList<>();
        for (CitMssrGrid jmsdEntity : listJmsdxx) {
            CitMssrGridVo jmsdVo = new CitMssrGridVo();
            BeanUtils.copyProperties(jmsdEntity, jmsdVo);
            jmsdVo.setXh(jmsdEntity.getEwbhxh());
            listJmsdxxVo.add(jmsdVo);
        }
        //5.主表数据-其他信息
        List<CitQtxx> listQtxx = this.queryQtxx(taxNo, skssqq, skssqz);
        if (CollectionUtil.isEmpty(listQtxx)) {
            CitQtxx qtxx = new CitQtxx();
            qtxx.setNsrsbh(taxNo);
            qtxx.setSkssqq(skssqq);
            qtxx.setSkssqz(skssqz);
            listQtxx.add(qtxx);
        }

        JSONObject result = new JSONObject();
        // entity => vo
        CitNsrxxVo nsrxx = new CitNsrxxVo();
        BeanUtils.copyProperties(listNsrxx.get(0), nsrxx);
        CitYhfbxxVo yhfbxx = new CitYhfbxxVo();
        BeanUtils.copyProperties(listYhfbxx.get(0), yhfbxx);
        CitSbbxxVo sbbxx = new CitSbbxxVo();
        BeanUtils.copyProperties(listSbbxx.get(0), sbbxx);

        String bnljzjkcjednsStr = iCitZcjszjkcmxbService.getBnljzjkcjedns(param.getNsrsbh(),param.getSkssqq(),param.getSkssqz());
        BigDecimal bnljzjkcjedns = new BigDecimal(bnljzjkcjednsStr);

        //3利润总额 + 4特定业务计算的应纳税所得额 - 5不征税收入- 6 资产加速折旧、摊销（扣除）调减额（填写A201020） - 行次7：免税收入、减计收入、所得减免等优惠金额累计 - 8所得减免 - 9弥补以前年度亏损累计
        String sjlreLj = getSjlreLj(new BigDecimal(sbbxx.getLrzeLj()),
                   new BigDecimal(sbbxx.getTdywjsdynssdeLj()),
                   new BigDecimal(sbbxx.getBzssrLj()),
                   bnljzjkcjedns,
                   new BigDecimal(sbbxx.getMssrLj()),
                   new BigDecimal(sbbxx.getSdjmLj()),
                    new BigDecimal(sbbxx.getMbyqndksLj()));
        //6行-纳税调减金额
        sbbxx.setSjlreLj(sjlreLj);
        sbbxx.setGdzcjszjkctjeLj(iCitZcjszjkcmxbService.getBnljzjkcjedns(param.getNsrsbh(),param.getSkssqq(),param.getSkssqz()));
        CitQtxxVo qtxx = new CitQtxxVo();
        BeanUtils.copyProperties(listQtxx.get(0), qtxx);
        if (isJson) {
            result.put("nsrxx", JSON.toJSONString(nsrxx)); 
            result.put("yhfbxx", JSON.toJSONString(yhfbxx)); 
            result.put("sbbxx", JSON.toJSONString(sbbxx)); 
            result.put("mssrxx", JSON.toJSONString(listMssrxxVo)); 
            result.put("sdjmxx", JSON.toJSONString(listSdjmxxVo)); 
            result.put("jmsdxx", JSON.toJSONString(listJmsdxxVo)); 
            result.put("qtxx", JSON.toJSONString(qtxx)); 
        } else {
            result.put("nsrxx", nsrxx); 
            result.put("yhfbxx", yhfbxx); 
            result.put("sbbxx", sbbxx); 
            result.put("mssrxx", listMssrxxVo); 
            result.put("sdjmxx", listSdjmxxVo); 
            result.put("jmsdxx", listJmsdxxVo); 
            result.put("qtxx", qtxx); 
        }
        log.info("返回前端的[主表数据]为：" + result.toString());
        return JsonResult.success(result);
    }

    private String getSjlreLj(BigDecimal h3, BigDecimal h4, BigDecimal h5, BigDecimal h6, BigDecimal h7, BigDecimal h8, BigDecimal h9) {
        return h3.add(h4).subtract(h5).subtract(h6).subtract(h7).subtract(h8).subtract(h9).toString();
    }

    /**
     * 获取[主表数据-纳税人信息]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [主表数据-纳税人信息]
     */
    @Override
    public List<CitNsrxx> queryNsrxx(String taxNo, String skssqq, String skssqz) {
        CitNsrxx query = new CitNsrxx();
        query.setNsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitNsrxx> example = Example.of(query);
        return nsrxxDao.findAll(example);
    }
    
    /**
     * 获取[主表数据-优惠附表信息]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [主表数据-优惠附表信息]
     */
    @Override
    public List<CitYhfbxx> queryYhfbxx(String taxNo, String skssqq, String skssqz) {
        CitYhfbxx query = new CitYhfbxx();
        query.setNsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitYhfbxx> example = Example.of(query);
        return yhfbxxDao.findAll(example);
    }

    /**
     * 获取[主表数据-申报表信息]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [主表数据-申报表信息]
     */
    @Override
    public List<CitSbbxx> querySbbxx(String taxNo, String skssqq, String skssqz) {
        CitSbbxx query = new CitSbbxx();
        query.setNsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitSbbxx> example = Example.of(query);
        return sbbxxDao.findAll(example);        
    }
    
    /**
     * 获取[主表数据-优惠数据]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @param hc 行次
     * @return [主表数据-优惠数据]
     */
    private List<CitMssrGrid> queryMssrxx(String taxNo, String skssqq, String skssqz, String hc) {
        CitMssrGrid query = new CitMssrGrid();
        query.setNsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitMssrGrid> example = Example.of(query);
        List<CitMssrGrid> list = mssrxxDao.findAll(example);    
        List<CitMssrGrid> result = new ArrayList<>();
        for (CitMssrGrid entity : list) {
            if (entity.getEwbhxh().contains(hc + ".")) {
                result.add(entity);
            }
        }
        return result;
    }

    /**
     * 获取[主表数据-其他信息]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [主表数据-其他信息]
     */
    @Override
    public List<CitQtxx> queryQtxx(String taxNo, String skssqq, String skssqz) {
        CitQtxx query = new CitQtxx();
        query.setNsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitQtxx> example = Example.of(query);
        return qtxxDao.findAll(example);
    }
    
    /**
     * 获取[分配表的分支机构信息]-南航股份
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [分配表的分支机构信息]-南航股份
     */
    @Override
    public CitFzjgForm queryNhFzjgData(String taxNo, String skssqq, String skssqz) {
        CitZjgxxForm zjgxx = this.queryZjgxx(taxNo, skssqq, skssqz);
        if (zjgxx != null) {
            CitFzjgForm query = new CitFzjgForm();
            query.setZjgxxFormId(zjgxx.getId());
            query.setFzjgnsrsbh(taxNo);
            Example<CitFzjgForm> example = Example.of(query);
            List<CitFzjgForm> list = fzjgFormDao.findAll(example);
            if (CollectionUtil.isNotEmpty(list)) {
                return list.get(0);
            }
        }
        return null;
    }
    
    /**
     * 获取[分配表的总机构信息]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [分配表的总机构信息]
     */
    private CitZjgxxForm queryZjgxx(String taxNo, String skssqq, String skssqz) {
        CitZjgxxForm query = new CitZjgxxForm();
        query.setZjgnsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitZjgxxForm> example = Example.of(query);
        List<CitZjgxxForm> list = zjgxxFormDao.findAll(example);
        if (CollectionUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }
    
    /**
     * 获取[分配表的分支机构信息]
     * @param zjgxx 分配表的总机构信息
     * @return 分配表的分支机构信息
     */
    private List<CitFzjgForm> queryFzjgxx(CitZjgxxForm zjgxx) {
        CitFzjgForm query = new CitFzjgForm();
        query.setZjgxxFormId(zjgxx.getId());
        Example<CitFzjgForm> example = Example.of(query);
        return fzjgFormDao.findAll(example);
    }

    @Override
    public JsonResult<JSONObject> queryYhbm(String hc) {
        CitMssrBm query = new CitMssrBm();
        query.setHc(hc);
        Example<CitMssrBm> example = Example.of(query);
        List<CitMssrBm> list = mssrBmDao.findAll(example);
        List<CitMssrBmVo> data = new ArrayList<>();
        for (CitMssrBm db : list) {
            CitMssrBmVo entity = new CitMssrBmVo();
            BeanUtil.copyProperties(db, entity);
            entity.setSelected(false);
            entity.setYhswsx(db.getDm());
            entity.setSsjmxzDm(db.getXz());
            entity.setEwbhgjz(db.getXm());
            entity.setYhjmje(BigDecimal.ZERO);
            data.add(entity);
        }
        JSONObject result = new JSONObject();
        result.put("yhbm", data); 
        log.info("返回前端的[主表优惠编码数据]为：" + result.toString());
        return JsonResult.success(result);
    }
    @Override
    public InitDataVo getInitData(CitQueryParam param,UserVo user){
        CitSendParam param2 = new CitSendParam();
        BeanUtils.copyProperties(param, param2);
        CitDeclareRecord record = this.queryDeclareRecord(param2);

        //获取期初数据
        InitDataVo dataInit = null;
        if (record == null) {
            try {
                JsonResult<InitDataVo> initResult = initDataService.getInitData(param, user);
                List<InitDataVo> datasInit = initResult.getData();
                if (CollectionUtil.isNotEmpty(datasInit)) {
                    dataInit = datasInit.get(0);
                }
            } catch (Exception e) {
                log.error("获取期初数据异常，" + e.getMessage(), e);
            }
        }
        return dataInit;
    }
    /**
     * 检查数据有效性
     * @param nsrsbh 纳税人识别号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     */
    private void checkData(String nsrsbh, String skssqq, String skssqz) {
        if (StringUtil.isEmpty(nsrsbh)) {
            throw new CitBizException(CitBizException.NSRSBH_NOT_NULL, "税号不能为空");
        }
        //获取申报进度
        CitSendParam param = new CitSendParam();
        param.setNsrsbh(nsrsbh);
        param.setSkssqq(skssqq);
        param.setSkssqz(skssqz);
        CitDeclareRecord record = this.queryDeclareRecord(param);
        if (record != null) {
            //throw new CitBizException(CitBizException.NO_UPDATE_AFTER_DECLARATION, "该数据已进行了申报，禁止更新");
        }        
    }
}
